package com.jlkf.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.github.pagehelper.PageHelper;
import com.jlkf.common.Constant;
import com.jlkf.common.rong.models.CodeSuccessResult;
import com.jlkf.common.rong.models.TokenResult;
import com.jlkf.common.rong.util.RongCloud;
import com.jlkf.dao.*;
import com.jlkf.pojo.*;
import com.jlkf.service.UserService;
import com.jlkf.service.util.*;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.HttpRequestUtil;
import com.platform.server.util.MD5Util;
import com.platform.server.util.RandomUtil;

import io.practiceinsight.pinpayments.pojo.ErrorMessage;
import io.practiceinsight.pinpayments.pojo.ErrorResponse400;
import io.practiceinsight.pinpayments.pojo.ErrorResponseCard;
import io.practiceinsight.pinpayments.pojo.ResponseCard;
import io.practiceinsight.pinpayments.pojo.ResponseCharges;
import io.practiceinsight.pinpayments.pojo.ResponseTransfers;
import io.practiceinsight.pinpayments.utils.PinPayHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private AuthcodeMapper authCodeMapper;
	@Autowired
	private UserBrankMapper userBrankMapper;
	@Autowired
	private UserCouponMapper userCouponMapper;
	@Autowired
	private DriverAccessoryMapper driverAccessoryMapper;
	@Autowired
	private OrderItemsMapper orderItemsMapper;
	@Autowired
	private PinpayRecordMapper pinpayRecordMapper;
	@Autowired
	private ConfigManagerMapper configManagerMapper;

	@Override
	public ReturnData sendSMS(String telephone, Integer type, Integer platform) {
		Map<String, Object> params = new HashMap<>();
		params.put("username", "fabtech");// 发送短信与登录后台的用户名
		params.put("password", "fabtech2017");// 登录密码
		// String s =telephone.substring(0, 1);
		/*
		 * if("0".equals(s)){ telephone =telephone.substring(1,
		 * telephone.length()); }
		 */
		params.put("to", "614" + telephone); // 0400111222,0400222333
		params.put("from", "fab");// 发送者
		String vCode = RandomUtil.getRandomNumberString(4);// 4个字符短信验证码
		if (1 == type) {// 注册
			params.put("message", "Your registration verification code is:" + vCode);
		} else if (2 == type) {// 修改手机号
			params.put("message", "The verification code of your change of mobile phone number is:" + vCode);
		} else if (3 == type) {// 司机端发送验证码
			params.put("message", "This login verification code is:" + vCode);
		} else if (4 == type) {// 我是乘客 网站登录验证码
			params.put("message", "This login verification code is:" + vCode);
		} else if (5 == type) {// 企业网站修改密码
			params.put("message", "The verification code of your change of mobile phone number is:" + vCode);
		} else {
			params.put("message", "The verification code  is:" + vCode);
		}
       
		params.put("delay", "0");// 延迟时间
		// url = https://api.smsbroadcast.com.au/api-adv.php //发送消息的路径
		// username fabtech password fabtech2017 to 614[国际]+电话号码 from【发送者的电话】
		// message 【消息内容】 默认字符为160个 maxsplit【短信的最大长度】
		// delay 延迟时间 【单位 ：秒】
		try {
			// 发送消息返回的内容
			String result = HttpRequestUtil.sendRequestByGet("https://api.smsbroadcast.com.au/api-adv.php", params);
			/**
			 * OK : 61400111222:2942263 --------- --- OK : This message was
			 * accepted BAD:0400abc111 :Invalid Number ----------BAD: This
			 * message was invalid. (eg, invalid phone number) ERROR: Username
			 * or password is incorrect. --ERROR: The request failed. (eg, wrong
			 * username/password or missing a required parameter )
			 */
			// 字符串中包含OK
			/* if(result.indexOf("OK")!=-1){ } */
			if (result.indexOf("BAD") != -1) {// 号码无效 发送不成功
				String[] strlist = result.split(":");
				String errorMessage = strlist[2];// 错误提示消息
				return new ReturnData(201, errorMessage);
			} else if (result.indexOf("ERROR") != -1) {// 错误
				String[] strlist = result.split(":");
				String errorMessage = strlist[1];// 错误消息
				return new ReturnData(201, errorMessage);
			}else {
				Authcode ac = new Authcode();
				ac.setCreateDate(new Date());
				ac.setPhone(telephone);
				ac.setVcode(vCode);
				ac.setPlatform(platform);
				int code = authCodeMapper.insertSelective(ac);// 保存验证码发送时间 与记录
				if(code==0){
					return new ReturnData(209,"Failed to send verification code");
				}
				return new ReturnData(vCode, 200, "success");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 是否注册
	@Override
	public ReturnData isRegistered(String telephone) {
		Map<String, Object> map = new HashMap<>();
		map.put("telephone", telephone);
		map.put("identity", 1);
		map.put("isDeleted", 0);
		try {
			List<User> list = userMapper.getLogin(map);
			if (list.size() > 0) {
				return new ReturnData(false, 201, "Has been registered!");
			}
			return new ReturnData(true, 200, "Not registered");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 登录
	@Override
	public ReturnData login(String json) {
		User u = StringTools.json2Obj(json, User.class);
		String result = CheckParams.checkUserLogin(u);
		if (!StringTools.isEmpty(result)) {
			return new ReturnData(201, result);
		}
		if(StringTools.isEmpty(u.getUseEquipment())){//设备令牌为空
			return new ReturnData(290,LanguageUtils.returnLan(u.getLanguage(), "UseEquipment_empty"));
		}
		Map<String, Object> map = new HashMap<>();
		String password = u.getPassword();
		map.put("telephone", u.getTelephone());
		map.put("identity", 1);// 用户端
		map.put("isDeleted", 0);// 未被删除的账号
		try {
			List<User> list1 = userMapper.getLogin(map);
			if (list1.size() == 0) {
				return new ReturnData(204, LanguageUtils.returnLan(u.getLanguage(), "not_registered"));
			}
			String newPass = MD5Util.getMD5(password);// 加密之后的密码
			map.put("password", newPass);
			List<User> list = userMapper.getLogin(map);
			if (list.size() == 0) {
				return new ReturnData(202, LanguageUtils.returnLan(u.getLanguage(), "password_mistake"));
			}
			User uu = list.get(0);
			if (uu.getIsSethonor() == 2) {// 账号被封
				return new ReturnData(206, LanguageUtils.returnLan(u.getLanguage(), "account_sealed"));
			}
		
			RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
				 TokenResult userGetTokenResult = rongCloud.user.getToken(uu.getId().toString(), uu.getFirstName(), uu.getPicture());
				 if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
					 uu.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
				 }
				    uu.setIsOnline(1);
					uu.setLoginTime(new Date());
					uu.setUseEquipment(u.getUseEquipment());
					int n = userMapper.updateByPrimaryKeySelective(uu);
					if (n == 0) {
						return new ReturnData(208, "The last login time failed");
					}
			uu.setPassword(null);
			return new ReturnData(uu, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 注册
	public ReturnData registration(String json) throws Exception {
		User u = StringTools.json2Obj(json, User.class);
		if (u == null) {
			return new ReturnData(208, LanguageUtils.returnLan(1, "list_empty"));
		}
		if (StringTools.isEmpty(u.getTelephone())) {
			return new ReturnData(209, LanguageUtils.returnLan(u.getLanguage(), "phone_length"));
		}
		if(StringTools.isEmpty(u.getUseEquipment())){//设备令牌为空
			return new ReturnData(290,LanguageUtils.returnLan(u.getLanguage(), "UseEquipment_empty"));
		}
		Map<String, Object> map = new HashMap<>();
		map.put("telephone", u.getTelephone());
		map.put("identity", 1);// 用户端
		map.put("isDeleted", 0);// 判断该用户 没有被删除 是否删除 0否 1是
		String msg = LanguageUtils.returnLan(u.getLanguage(), "registered_successfully");
		int code = 200;
//		try {
			List<User> list1 = userMapper.getLogin(map);// 查询电话是否已被使用
			if (list1.size() > 0) {
				// 判断这个账号是否已经被删除 没有被删除 则不能注册
				return new ReturnData(204, LanguageUtils.returnLan(u.getLanguage(), "registered"));
			} else {// 作为新用户
				List<Authcode> list = authCodeMapper.getList(map);
				if (list.size() > 0) {
					String vCode = list.get(0).getVcode();
					if (vCode.equals(u.getvCode())) {// 验证码一致
						Date d = new Date();
						// 毫秒ms
						long diff = d.getTime() - list.get(0).getCreateDate().getTime();
						long diffMinutes = diff / (60 * 1000) % 60;
						if (diffMinutes <= 10) {// 十分钟之内的验证码 有效
							u.setIdentity(1);
							u.setCreateTime(new Date());
								String password = u.getPassword();
								if (!StringTools.isEmpty(password) && password.length() < 6 && password.length() > 18) {
									return new ReturnData(207,
											LanguageUtils.returnLan(u.getLanguage(), "password_length"));
								}
								String ic= u.getInviattionCode();
								System.out.println("用户填的司机的邀请码======"+ic);
								u.setBeinvitecode(ic);// 用户填写的邀请码是别人的邀请码
								// 保存邀请他的人的邀请码
								// 后期会给他赠送
								String newPass = MD5Util.getMD5(password);
								u.setPassword(newPass);
								String inviattionCode = RandomUtil.getRandomString(8);
								map.remove("inviattionCode");
								map.put("inviattionCode", inviattionCode);
								List<User> list4 = userMapper.getLogin(map);// inviattionCode是否已被使用
								if (list4.size() > 0) {
									u.setInviattionCode(RandomUtil.getRandomString(8));
								} else {
									u.setInviattionCode(inviattionCode);
								}
								u.setPicture("http://"+Constant.SERVER_NAME+"//file//fab//user.jpg");
								int num = userMapper.insertSelective(u);
								if (num == 0) {
									code = 201;
									msg = LanguageUtils.returnLan(u.getLanguage(), "registration_failed");
								} else{//注册成功账号之后去获取融云账号的token
									List<User>  list2=userMapper.getLogin(map);
									RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
									 if(list2.size()>0){
										 TokenResult userGetTokenResult = rongCloud.user.getToken(list2.get(0).getId().toString(), list2.get(0).getFirstName(), "http://"+Constant.SERVER_NAME+"//file//fab//user.jpg");
										 if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
											 User uus = list2.get(0);
											 uus.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
											int nus= userMapper.updateByPrimaryKeySelective(uus);
											if(nus==0){
												code=305;msg = LanguageUtils.returnLan(u.getLanguage(), "registration_failed");
											}
										 }else{
											 code=306;msg ="Integrating cloud response message :"+userGetTokenResult.getErrorMessage() ;
										 }
									 }
								}
							}
						}else {
							code = 206;// 环信账号注册失败
							msg = LanguageUtils.returnLan(u.getLanguage(), "code_expired");
						}
					} else {
						code = 206;// 环信账号注册失败
						msg = LanguageUtils.returnLan(u.getLanguage(), "code_error");
					}
			}
			if (code != 200) {
				u = null;
			}else{
				List<User> list2 = userMapper.getLogin(map);
				if (list2.size() > 0) {
					u = list2.get(0);
					u.setPassword(null);
				}
			}
			return new ReturnData(u, code, msg);
	}

	@Override
	public ReturnData updateUser(String json) {
		User u = StringTools.json2Obj(json, User.class);
		String result = CheckParams.checkUserUpdate(u);
		if (!StringTools.isEmpty(result)) {
			return new ReturnData(201, result);
		}
		try {RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);//融云
			if(u.getPicture()!=null||u.getFirstName()!=null){//修改了用户的头像
				CodeSuccessResult userRefreshResult = rongCloud.user.refresh(u.getId().toString(), u.getFirstName(), u.getPicture());
				System.out.println("rongCloud_refresh:  " + userRefreshResult.toString());
				if(userRefreshResult.getCode()!=200){
					return new ReturnData(300,LanguageUtils.returnLan(u.getLanguage(), "update_fail"));
				}
			}
			int num = userMapper.updateByPrimaryKeySelective(u);
			if (num == 0) {
				return new ReturnData(202, LanguageUtils.returnLan(u.getLanguage(), "update_fail"));
			}
			return new ReturnData(200, LanguageUtils.returnLan(u.getLanguage(), "update_success"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public ReturnData emailIsUse(String email, Integer language) {
		if (!RegexUtil.isEmail(email)) {
			return new ReturnData(206, LanguageUtils.returnLan(language, "email_format"));
		}
		Map<String, Object> map = new HashMap<>();
		map.put("email", email);
		try {
			List<User> list = userMapper.getLogin(map);
			if (list.size() > 0) {
				return new ReturnData(false, 201, LanguageUtils.returnLan(language, "email_registered"));
			}
			return new ReturnData(true, 200, LanguageUtils.returnLan(language, "email_not_registered"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public ReturnData myInformation(Long uId) {
		try {
			User u = userMapper.selectByPrimaryKey(uId);
			if(u!=null){
				u.setPassword(null);
			}
			return new ReturnData(u, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 我的账户
	@Override
	public ReturnData myAccount(Long uId) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		map.put("uId", uId);
		map.put("isUse", 1);// 未使用的优惠劵查询
		try {
			List<UserBrank> list = userBrankMapper.getUserBrank(map);
			map1.put("bankCardQuantity", list.size());// 我绑定的银行卡数量
			List<UserCoupon> couponlist = userCouponMapper.getCoupon(map);// 我的未使用优惠劵数量
			map1.put("couponQuantity", couponlist.size());
			return new ReturnData(map1, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 我的银行卡列表
	@Override
	public ReturnData myBrankList(Long uId) {
		Map<String, Object> map = new HashMap<>();
		map.put("uId", uId);
		try {
			List<UserBrank> list = userBrankMapper.getUserBrank(map);
			return new ReturnData(list, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 设置默认免密支付卡
	@Override
	public ReturnData setTheDefault(Long ubId, Long uId) {
		Map<String, Object> map = new HashMap<>();
		map.put("uId", uId);
		boolean flag = true;
		try {
			List<UserBrank> list = userBrankMapper.getUserBrank(map);
			for (UserBrank ub : list) {
				if (ub.getUbId().equals(ubId)) {
					ub.setIsDefault(1);// 是否是默认支付卡 1默认 2非默认
				} else {
					ub.setIsDefault(2);// 是否是默认支付卡 1默认 2非默认
				}
				int num = userBrankMapper.updateByPrimaryKeySelective(ub);
				if (num == 0) {
					flag = false;
				}
			}
			if (!flag) {
				return new ReturnData(201, LanguageUtils.returnLan(2, "set_fail"));
			}
			return new ReturnData(200, LanguageUtils.returnLan(2, "set_success"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Autowired
	private JedisPool jedisPool; 
	@Override
	public ReturnData addUserBrank(String json) {
		UserBrank ub = StringTools.json2Obj(json, UserBrank.class);
		String result = CheckParams.checkUserBrank(ub);
		if (!StringTools.isEmpty(result)) {
			return new ReturnData(201, result);
		}
		String ubBrankNo = ub.getUbBrankNo();
		Map<String, Object> map = new HashMap<>();
		map.put("ubBrankNo", ubBrankNo);
		ub.setCreateTime(new Date()); int code=200;String msg="success";
		Jedis jedis = null;
		if(jedis == null){
			jedis=	jedisPool.getResource();
		}
		try {
		/*	List<UserBrank> list = userBrankMapper.getUserBrank(map);
			if (list.size() > 0) {
				return new ReturnData(205, LanguageUtils.returnLan(ub.getLanguage(), "brankNo_use"));
			}*/
			if(!StringTools.isEmpty(ub.getTheCardholder())){
				String theCardHolder = ub.getTheCardholder();
				theCardHolder=theCardHolder.trim();
				if(theCardHolder.indexOf(" ") != -1){
				}else{
					return new ReturnData(205, LanguageUtils.returnLan(ub.getLanguage(), "cardholder_name"));
				}
			}
			 if(ub.getUbId()!=null){
	   				int num = userBrankMapper.updateByPrimaryKey(ub);
	   				if (num == 0) {
	   					return new ReturnData(202, "fail");
	   				}
	   				return new ReturnData(200, "update success");
	   			}
			 
			 ConfigManager cm=null;
	   			String configManager=jedis.get("configManager");
	   			if(StringTools.isEmpty(configManager)){
	   				 cm = configManagerMapper.selectByPrimaryKey(1);
	   					JSONObject jo = JSONObject.fromObject(cm);
	   					jedis.set("configManager", jo.toString());
	   			}else{
	   				JSONObject jo = JSONObject.fromObject(configManager);
	   				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
	   			}
			 
			 
			/**
			 * 背面三位 cvv 过期时间 05/2023 card_expiry 持卡人 card_holder 银行卡号
			 * card_number
			 */
			User user = userMapper.selectByPrimaryKey(ub.getuId());
			String yearAndMon=ub.getExpirationTime();
			String[] ym=yearAndMon.split("/");
	      //////////用户支付 totalPrice1 金额  /////////
	    	Map<String, String> sendMap=new HashMap<>();
	    	Integer tos=(int) (100);//添加银行卡时扣取用户1元钱
	    	sendMap.put("amount", tos+"");//需要支付的金额
	    	sendMap.put("currency", "AUD");
	    	sendMap.put("description", "fab Card Authentication ");//收取金额的原因
	    	sendMap.put("email", user.getEmail());
	    	sendMap.put("ip_address", ub.getCustomer_ip());
	    	sendMap.put("card[number]", ub.getUbBrankNo());
	    	sendMap.put("card[expiry_month]", ym[0]);
	    	sendMap.put("card[expiry_year]", ym[1]);
	    	sendMap.put("card[cvc]", ub.getAfterThree());
	    	sendMap.put("card[name]", ub.getTheCardholder());
//	    	sendMap.put("card[address_line1]", ub.getAddressLine1());
//	      	sendMap.put("card[address_city]", ub.getAddressCity());
	    	sendMap.put("card[address_country]", "Australia");//澳大利亚
	    	 String jrc=null;
	    	Map<String,Object> resut=PinPayHttpUtils.sendPinPayChargesPost(sendMap);//支付
	  	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
    		   jrc = JSONObject.fromObject(rc).toString();
    		  
   				int num = userBrankMapper.insertSelective(ub);
   				if (num == 0) {
   					return new ReturnData(202, "fail");
   				}
//   				List<ConfigManager> cm = configManagerMapper.getList();
   				if (cm!=null) {//添加成功之后发送短信 及时通知
   					sendSMS(user.getTelephone(),  9, cm.getAdd_card_message());
   				}
   				return new ReturnData(200, "success");
   		}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
   			String error="";
   			if(rc!=null){
   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
                for(ErrorMessage ee:liMessage){
              	  error+=ee.getMessage()+" ; "; 
                }
   			}
   			jrc=error;code=(int)resut.get("code");msg="The card information you’ve provided is invalid";
   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
   			jrc = JSONObject.fromObject(rc).toString();code=(int)resut.get("code");msg="The card information you’ve provided is invalid";
		}
    	  PinpayRecord ppr = new PinpayRecord(null,jrc,(int)resut.get("code"),new Date(),4);//支付记录
		  pinpayRecordMapper.insertSelective(ppr);
			
			return new ReturnData(code, msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
	
	//发送自定义内容短信
	public ReturnData sendSMS(String telephone,  Integer platform,String context) {
		Map<String, Object> params = new HashMap<>();
		params.put("username", "fabtech");// 发送短信与登录后台的用户名
		params.put("password", "fabtech2017");// 登录密码
		params.put("to", "614" + telephone); // 0400111222,0400222333
		params.put("from", "fab");// 发送者
		params.put("message", context);
		params.put("delay", "0");// 延迟时间
		params.put("maxsplit", "5");
		// url = https://api.smsbroadcast.com.au/api-adv.php //发送消息的路径
		// username fabtech password fabtech2017 to 614[国际]+电话号码 from【发送者的电话】
		// message 【消息内容】 默认字符为160个 maxsplit【短信的最大长度】
		// delay 延迟时间 【单位 ：秒】
		try {
			// 发送消息返回的内容
			String result = HttpRequestUtil.sendRequestByGet("https://api.smsbroadcast.com.au/api-adv.php", params);
			/**
			 * OK : 61400111222:2942263 --------- --- OK : This message was
			 * accepted BAD:0400abc111 :Invalid Number ----------BAD: This
			 * message was invalid. (eg, invalid phone number) ERROR: Username
			 * or password is incorrect. --ERROR: The request failed. (eg, wrong
			 * username/password or missing a required parameter )
			 */
			// 字符串中包含OK
			/* if(result.indexOf("OK")!=-1){ } */
			if (result.indexOf("BAD") != -1) {// 号码无效 发送不成功
				String[] strlist = result.split(":");
				String errorMessage = strlist[2];// 错误提示消息
				return new ReturnData(201, errorMessage);
			} else if (result.indexOf("ERROR") != -1) {// 错误
				String[] strlist = result.split(":");
				String errorMessage = strlist[1];// 错误消息
				return new ReturnData(201, errorMessage);
			}else {
				Authcode ac = new Authcode();
				ac.setCreateDate(new Date());
				ac.setPhone(telephone);
				ac.setVcode(context);
				ac.setPlatform(platform);
				int code = authCodeMapper.insertSelective(ac);// 保存验证码发送时间 与记录
				if(code==0){
					return new ReturnData(209,"Failed to send verification code");
				}
				return new ReturnData( 200, "success");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}
	//
	@Override
	public ReturnData getMyCoupons(Long uId, Integer pageNo, Integer pageSize) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		if (RegexUtil.isNull(pageNo)) {
			pageNo = 1;
		}
		if (RegexUtil.isNull(pageSize)) {
			pageSize = 10;
		}
		map.put("uId", uId);
		try {
			PageHelper.startPage(pageNo, pageSize);
			map.put("isUse", 1);
			List<UserCoupon> list = userCouponMapper.getUserCoupon(map);
			map.remove("isUse");
			map.put("isUse", 2);
			Integer count = userCouponMapper.getCouponCount(map);
			map1.put("couponList", list);
			map1.put("deductible", count);
			return new ReturnData(map1, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 已使用优惠劵
	@Override
	public ReturnData getMyUseCoupons(Long uId, Integer pageNo, Integer pageSize) {
		if (pageNo==null) {
			pageNo = 1;
		}
		if (RegexUtil.isNull(pageSize)) {
			pageSize = 10;
		}
		Map<String, Object> map = new HashMap<>();
		map.put("uId", uId);
		map.put("isUse", 2);
		map.put("orders", 1);//排序按照时间最新的在最上面
		try {
			PageHelper.startPage(pageNo, pageSize);
			List<UserCoupon> list = userCouponMapper.getCoupon(map);
			return new ReturnData(list, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public ReturnData getDriverCar(Long uId) {
		try {
			List<DriverAccessory> list = driverAccessoryMapper.getUserCars(uId);
			return new ReturnData(list, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public ReturnData updateDriverOnlineStatus(Long uId, Integer isOnline) {
		User u = new User();
		u.setId(uId);
		u.setIsOnline(isOnline);
		u.setIs_last_order(1);// 不是最后一单
		try {
			int num = userMapper.updateByPrimaryKeySelective(u);
			if (num == 0) {
				return new ReturnData(201, "Alteration Failed");
			}
			return new ReturnData(200, "Alteration Completed");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public ReturnData facebookIsRegistered(String openId, Integer language) {
		Map<String, Object> map = new HashMap<>();
		map.put("facebookOpenId", openId);
		try {
			List<User> list = userMapper.getLogin(map);
			if (list.size() > 0) {
				if (!StringTools.isEmpty(list.get(0).getTelephone())) {// 判断电话号码是否为空
					User u = list.get(0);
					u.setPassword(null);
					RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
					 TokenResult userGetTokenResult = rongCloud.user.getToken(u.getId().toString(), u.getFirstName(), u.getPicture());
					 if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
						 u.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
						 u.setLoginTime(new Date());
							int n = userMapper.updateByPrimaryKeySelective(u);
							if (n == 0) {
								return new ReturnData(208, "The last login time failed");
							}
					 }
					return new ReturnData(u, 200, "Has been binding!");
				}
			}
			return new ReturnData(null, 201, "Not binding");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public ReturnData getMyPortraitAndName(Long uId) {
		Map<String, Object> map = new HashMap<>();
		String name = "";
		String picture = "";
		try {
			User u = userMapper.selectByPrimaryKey(uId);
			if (u != null) {
				name = u.getName();
				picture = u.getPicture();
			}
			map.put("name", name);
			map.put("uId", uId);
			map.put("picture", picture);
			return new ReturnData(map, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}

	}

	@Override
	public ReturnData driverLogin(String telephone, String vCode, String auroraAlias,String useEquipment) {
		if (StringTools.isEmpty(telephone)) {
			return new ReturnData(211, "The phone number can't be empty");
		}
		if (StringTools.isEmpty(vCode)) {
			return new ReturnData(210, "The vCode  can't be empty");
		}
		if(StringTools.isEmpty(useEquipment)){//设备令牌为空
			return new ReturnData(290,"The device token is empty.");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("telephone", telephone);
		map.put("identity", 2);// 用户端
		map.put("isDeleted", 0);// 判断该用户 没有被删除 是否删除 0否 1是
		try {
			//
			List<User> list =userMapper.getLogin(map);
//			List<User> list = userMapper.getDriverLogin(map);//
			if (list.size() > 0) {
				map.put("phone", telephone);// 查询验证码
				map.put("platform", 2);
				List<Authcode> list1 = authCodeMapper.getList(map);// 验证码
				if (list1.size() > 0) {
					String vCode1 = list1.get(0).getVcode();
					if (vCode1.equals(vCode)) {// 验证码一致
						Date d = new Date(); // 毫秒ms
						long diff = d.getTime() - list1.get(0).getCreateDate().getTime();
						long diffMinutes = diff / (60 * 1000) % 60;
						if (diffMinutes <= 10) {// 十分钟之内的验证码 有效
							User u = list.get(0);
							if (u.getIsDeleted() == 2) {// 账号被封
								return new ReturnData(209, "You account has been suspended.");
							}
							u.setDriverStatus(1);//司机审核状态为审核成功
							u.setAuroraAlias(auroraAlias);
							RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
							 TokenResult userGetTokenResult = rongCloud.user.getToken(u.getId().toString(), u.getFirstName(), u.getPicture());
							 if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
								 u.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
								 u.setLoginTime(new Date());
							 }
							 u.setUseEquipment(useEquipment);
							 u.setIs_last_order(1);
							int n = userMapper.updateByPrimaryKeySelective(u);
							if(n==1){
								int carCount=driverAccessoryMapper.getCarCount(u.getId());
								u.setCarCount(carCount);
								return new ReturnData(u, 200, "success!");// 验证码已过期
							}else{
								return new ReturnData(u, 230, "update fail!");// 验证码已过期
							}
						} else {
							return new ReturnData(201, "Verification code expired");// 验证码已过期
						}
					} else {
						return new ReturnData(208, "Verification code error");// 验证码错误
					}
				} else {
					return new ReturnData(209, "Resend verification code");// 请先发送验证码
				}
			} else {
				return new ReturnData(201, "Account does not exist");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object isLastOrder(Long uId) {
		try {
			User u = userMapper.selectByPrimaryKey(uId);
			if (u != null && u.getIs_last_order().equals(1)) {
				u.setIs_last_order(2);
			}
			u.setIsOnline(2);// 离线
			int num = userMapper.updateByPrimaryKeySelective(u);
			if (num == 0) {
				return new ReturnData(201, "fail");
			}
			return new ReturnData(200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object deleteUserBrank(Long ubId) {
		try {
			int num = userBrankMapper.deleteByPrimaryKey(ubId);
			if (num == 0) {
				return new ReturnData(201, "delete fail");
			}
			return new ReturnData(200, "delete success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 用户端 忘记密码
	@Override
	public Object forgetPassword(String telephone, String vCode, String password, Integer language) {
		Map<String, Object> map = new HashMap<>();
		map.put("telephone", telephone);
		map.put("identity", 1);//普通用户
		User uu = null;
		try {
			List<Authcode> list = authCodeMapper.getList(map);
			if (list.size() > 0) {
				if (!vCode.equals(list.get(0).getVcode())) {// 验证码一致
					return new ReturnData(204, "Verification code error");
				}
				if (password.length() > 18 || password.length() < 4) {
					return new ReturnData(206, LanguageUtils.returnLan(language, "password_length"));
				}
				Date d = new Date();
				// 毫秒ms
				long diff = d.getTime() - list.get(0).getCreateDate().getTime();
				long diffMinutes = diff / (60 * 1000) % 60;
				if (diffMinutes <= 10) {// 十分钟之内的验证码 有效
					List<User> list1 = userMapper.getLogin(map);
					if (list1.size() == 0) {
						return new ReturnData(204, LanguageUtils.returnLan(language, "password_mistake"));
					}
					String newPass = MD5Util.getMD5(password);
					map.put("password", newPass);
					uu = list1.get(0);
					uu.setPassword(newPass);
					int nu = userMapper.updateByPrimaryKeySelective(uu);
					uu.setPassword(null);
					return new ReturnData(uu, 200, "success");
				} else {
					return new ReturnData(208, LanguageUtils.returnLan(language, "code_expired"));
				}
			} else {
				return new ReturnData(202, "Verification code does not exist");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object exitLogin(Long id, Integer isOnline, Integer language) {
		if(RegexUtil.isNull(language)){
			return new ReturnData(201,"language Can't be empty");
		}
		 try {
			User user = new User();
			user.setId(id);
			user.setIsOnline(isOnline);
			user.setExitTime(new Date());
			int num=userMapper.updateByPrimaryKeySelective(user);
			if(num==0){
				return new ReturnData(202,LanguageUtils.returnLan(language, "exit_login_fail"));
			}
			return new ReturnData(200,LanguageUtils.returnLan(language, "exit_login_success"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object getRongColud(Long uId) {
		try {
			User u = userMapper.selectByPrimaryKey(uId);
			Map<String,Object> map = new HashMap<>();
			map.put("id", uId);
			map.put("rongCloudToken", u.getRongCloudToken());
			map.put("name", u.getFirstName());
			map.put("picture", u.getPicture());
			return new ReturnData(map,200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

}
